package com.wy.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.wy.entity.User;
import com.wy.util.Constant;
import com.wy.util.security.CookieUtil;

@Namespace("/")
@ParentPackage("custom-default")
//@InterceptorRefs(@InterceptorRef("checkLoginStack"))
//@Results({@Result(name="login",type="redirect",location="/login.jsp")})
public class LoginAction extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	private static final String USER_SESSION_KEY = Constant.USER_SESSION_KEY;
	private User user;
	private String remenberMe;
	private String responseMsg;
	private Integer state;

//	@Action(value="login",results={@Result(name="success",type="redirectAction",location="home"),
//								   @Result(name="input",location="/login.jsp")})
	@Action(value="login",results={@Result(name="success",type="json",params={"responseMsg","state"})})
	public String login(){
//		request = getRequest();
		session = getSession();
		response = getResponse();
		
		if(user == null){
			state = 0;
			responseMsg = "请先登录";
//			return INPUT;
		}else if(user.getUsername().equals(user.getPassword())){
			session.setAttribute(USER_SESSION_KEY, user);
			//判断是否保存密码
			if(remenberMe != null && remenberMe.equals(Constant.USER_REMENBER_TAG)){
				//保存cookie
				CookieUtil.operateUserCookie(response,user,Constant.USER_COOKIE_MAXAGE);
			}else{
				//删除cookie
				CookieUtil.operateUserCookie(response,user,0);
			}
			state = 1;
		}else{
			state = 0;
			responseMsg = "用户名或密码不正确，请重新登录";
//			return INPUT;
		}
		return SUCCESS;
	}
	
	@Action(value="home",results={@Result(name="success",location="/jsp/home.jsp")})
	public String home(){
		session = getSession();
		if(session.getAttribute(USER_SESSION_KEY) == null){
			return LOGIN;
		}
		return SUCCESS;
	}
	
	@Action(value="logout",results={@Result(name="success",type="redirect",location="/login.jsp")})
	public String logout(){
		session = getSession();
		response= getResponse();
		if(session.getAttribute(USER_SESSION_KEY) != null){
			session.removeAttribute(USER_SESSION_KEY);
			//删除Cookie
			CookieUtil.operateUserCookie(response,user,0);
		}
		return SUCCESS;
	}
	
	
	
	
	/********getter and setter********/
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getResponseMsg() {
		return responseMsg;
	}
	public void setResponseMsg(String responseMsg) {
		this.responseMsg = responseMsg;
	}
	public String getRemenberMe() {
		return remenberMe;
	}
	public void setRemenberMe(String remenberMe) {
		this.remenberMe = remenberMe;
	}
	public Integer getState() {
		return state;
	}
	public void setState(Integer state) {
		this.state = state;
	}
	
}
